package cn.jingyuan.bee.utils.text.replacer;

import cn.jingyuan.bee.utils.lang.Chain;
import cn.jingyuan.bee.utils.text.StringsBuilder;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 字符串替换链，用于组合多个字符串替换逻辑
 */
public class ReplacerChain extends StringReplacer implements Chain<StringReplacer, ReplacerChain> {

    private final List<StringReplacer> replacers = new LinkedList<>();

    /**
     * 构造
     *
     * @param stringReplacers 字符串替换器
     */
    public ReplacerChain(StringReplacer... stringReplacers) {
        for (StringReplacer stringReplacer : stringReplacers) {
            addChain(stringReplacer);
        }
    }

    @Override
    public Iterator<StringReplacer> iterator() {
        return replacers.iterator();
    }

    @Override
    public ReplacerChain addChain(StringReplacer element) {
        replacers.add(element);
        return this;
    }

    @Override
    protected int replace(CharSequence string, int pos, StringsBuilder out) {
        int consumed = 0;
        for (StringReplacer stringReplacer : replacers) {
            consumed = stringReplacer.replace(string, pos, out);
            if (0 != consumed) {
                return consumed;
            }
        }
        return consumed;
    }

}
